package com.example.homework.controller;


import com.example.homework.domain.Actor;
import com.example.homework.domain.Movie;
import com.example.homework.domain.Role;
import com.example.homework.repository.ActorRepository;
import com.example.homework.repository.MovieRepository;
import com.example.homework.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    private MovieRepository movieRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private ActorRepository actorRepository;

    //角色新增页面
    @GetMapping(value = "/add/{movieId}")
    public String toAdd(Model model, @PathVariable Long movieId) {
        Movie movie = movieRepository.findOne(movieId);
        model.addAttribute("info", movie);
        return "role/add";
    }

    @PostMapping(value = "/add")
    public String doAdd(@RequestParam String roleName,@RequestParam String actorName,@RequestParam Long movieId){

        //通过电影ID获取电影信息
        Movie movie = movieRepository.findOne(movieId);

        Actor actor = new Actor();
        actor.setName(actorName);
        movie.addRole(actor, roleName);
        movieRepository.save(movie);

        return "redirect:/movie/detail/" + movieId;
    }

    //编辑界面
    @GetMapping(value = "/edit/{roleId}")
    public String toEdit(Model model,@PathVariable Long roleId){

        Role role = roleRepository.findOne(roleId);
        model.addAttribute("info",role);
        return "role/edit";
    }

    @PostMapping(value = "/edit")
    public String doEdit(@RequestParam String roleName,@RequestParam String actorName,@RequestParam Long role_id,@RequestParam Long movie_id){
        Role role = roleRepository.findOne(role_id);
        Actor actor = new Actor();
        actor.setName(actorName);

        role.setName(roleName);
        role.setActor(actor);

        roleRepository.save(role);


        return "redirect:/movie/detail/" + movie_id;
    }

    //删除
    @GetMapping(value = "/delete/{roleId}")
    public String delete(@PathVariable Long roleId){
        Role role = roleRepository.findOne(roleId);
        roleRepository.delete(roleId);

        return "redirect:/movie/detail/" + role.getMovie().getId();
    }

    //详细界面
    @GetMapping(value = "/detail/{id}")
    public String detail(Model model,@PathVariable Long id){
        Role role = roleRepository.findOne(id);
        model.addAttribute("info",role);
        return "role/detail";
    }

}
